let app = getApp();
let API_URL = app.globalData.API_URL;
let audioInfo = app.globalData.audioInfo;
let AppTiming = app.globalData.timingConif;

import importFormatTime from "../../utils/util.js";

Page({
  data: {
    qieGe: '',
    audioList: [],
    kitapCon: '', // 书籍信息
    openList: false,
    openTiming: false, // 定时
    playId: '', // 当前播放音频 ID
    currentSong: {}, // 当前播放的歌曲
    isPlaying: audioInfo.isPlaying, // 是否正在播放
    currentTime: '00:00', // 当前播放时间
    duration: '00:00', // 歌曲总时长（格式化后的字符串）
    progress: 0.0, // 进度条值（必须是数字）
    totalDuration: 642.624, // 歌曲总时长（秒数，必须是数字）
    postId: '', // 当前播放书籍 ID
    speed: 1,
    timingTime: [
      { id: 1, value: 30 },
      { id: 2, value: 50 },
      { id: 3, value: 70 },
      { id: 4, value: 90 },
      { id: 5, value: 120 },
    ],
    timingJi: [
      { id: 1, value: 2 },
      { id: 2, value: 10 },
      { id: 3, value: 15 },
      { id: 4, value: 20 },
      { id: 5, value: 30 },
    ],
    timingValue: 0,
    favoritesDialog: false,
    timingText: 'قىسىم',
    timingActive: 2, 
    timingChecked: false,
    timingTimeValue: '',
    timingJiValue: 0,
    poster: '',
    isShowLittleDrawing: false, // 最小画
    notificationShow: false, // 提示
    notificationMessage: 'سىستىمغا كىردىڭىز !',
    pageNo: 1,
    pageSize: 20,
    totalPage: 0,
    totalCount: 0,
    isLoginMask: false, 
    playAllMask: false,
  },

  loadMore() {
    if(this.data.pageNo == this.data.totalPage) return
    let pageNo = this.data.pageNo += 1
    this.setData({pageNo : pageNo})

    this.getAudio();
  },

  onShow() {
    this.setData({ speed: audioInfo.speed }) // 倍速赋值

    this.setData({ timingChecked: AppTiming.timingCheckedChange })
    if(AppTiming.timingTime !== '') {
      this.setData({ timingActive: AppTiming.timingType })
    } else if (AppTiming.timingJi > 0) {
      this.setData({ timingJiValue: AppTiming.timingJi })
    }
  },

  // 初始化音频上下文
  init() {
    let totalDuration = audioInfo.bgAudio.duration;
    audioInfo.formattedDuration = this.formatTime(totalDuration);
    
    this.setData({ isPlaying: audioInfo.isPlaying, playId: audioInfo.playId, duration: audioInfo.formattedDuration })
    
    audioInfo.bgAudio.onTimeUpdate(() => {
      console.log('onTimeUpdate 触发'); // 调试日志
      const currentTime = audioInfo.bgAudio.currentTime;
      let formattedTime = this.formatTime(currentTime);

      audioInfo.currentTime = currentTime;
      this.setData({
        currentTime: formattedTime, // 格式化当前时间
        progress: currentTime, // 更新进度条
      });

      formattedTime = this.formatTime(audioInfo.currentTime);
      this.setData({
        currentTime: formattedTime, // 格式化当前时间
        progress: audioInfo.currentTime, // 更新进度条
      });
    });

    audioInfo.bgAudio.onCanplay(() => {
      console.log('音频已加载'); // 调试日志
      this.checkDuration();      
    });

    // 播放完毕
    audioInfo.bgAudio.onEnded(() => {
      // 检查是否免费或者是否购买会员
      let isFree = this.data.kitapCon.is_free;
      if(isFree==1 && !app.globalData.isVIPAuthority) return this.setData({playAllMask: true});

      // 定集关闭音频播放
      if(AppTiming.timingJi > 0) {
        AppTiming.timingJi --;
        this.setData({ timingJiValue: AppTiming.timingJi })
      }
      let totalIndex = audioInfo.totalIndex
      let playCurrentIndex = audioInfo.playCurrentIndex
      let timingJi = AppTiming.timingJi // 定集
      if(totalIndex == playCurrentIndex || timingJi == 0) {
        AppTiming.timingCheckedChange = false
        return this.setData({ isPlaying: false, timingJiValue: 0, timingActive: 2, timingValue: 0,  });
      }

      // 找到当前音频在列表中的索引
      const currentIndex = this.data.audioList.findIndex(item => item.id === this.data.playId);
      // 计算下一首音频的索引
      const nextIndex = (currentIndex + 1) % this.data.audioList.length;
      audioInfo.playId = this.data.audioList[nextIndex].id;

      this.setData({
        playId: this.data.audioList[nextIndex].id
      })

      // 创建后台播放
      audioInfo.bgAudio = wx.getBackgroundAudioManager()
      audioInfo.bgAudio.title = this.data.audioList[nextIndex].name;
      audioInfo.bgAudio.singer = this.data.audioList[nextIndex].chapter_name;
      audioInfo.bgAudio.coverImgUrl = this.data.kitapCon.cover_wx_url;
      audioInfo.bgAudio.src = this.data.audioList[nextIndex].wx_url;
    })

    this.checkDuration();
  },

  // 检查 duration 的函数
  checkDuration() {

    if (audioInfo.bgAudio.duration !== undefined && audioInfo.bgAudio.duration !== 0) {

      let totalDuration = audioInfo.bgAudio.duration;
      audioInfo.formattedDuration = this.formatTime(totalDuration);

      totalDuration = audioInfo.bgAudio.duration;
      audioInfo.formattedDuration = this.formatTime(totalDuration);
      this.setData({
        totalDuration: totalDuration, // 总时长（秒数，必须是数字）
        duration: audioInfo.formattedDuration, // 格式化总时长
      });
    } else {
      setTimeout(this.checkDuration, 200);
    }
  },

  onLoad(options) {
    this.init();
    this.setData({ postId: options.postId });
    this.getBookInco();
    this.getAudio();
    this.isLogin();
    this.addpreview();
    if(AppTiming.secondsNoFormat > 0) this.countdown() , this.isTimingTime();
    if(AppTiming.timingJi > 0) this.isTimingJi();
  },

  // 如果开启定集关闭时
  isTimingJi() {
    for(let i of this.data.timingJi) {
      if(i.value == AppTiming.timingJi) {
        this.setData({ timingValue: i.id })
      }
    }
  },

  // 如果开启定时间开启时
  isTimingTime() {
    for(let i of this.data.timingTime) {
      if(i.value == AppTiming.timingTime) {
        this.setData({ timingValue: i.id })
      }
    }
  },

  // 格式化时间函数
  formatTime(seconds) {
    const minutes = Math.floor(seconds / 60); // 计算分钟数
    const remainingSeconds = Math.floor(seconds % 60); // 计算剩余的秒数
    const formattedMinutes = String(minutes).padStart(2, '0'); // 补零
    const formattedSeconds = String(remainingSeconds).padStart(2, '0'); // 补零
    return `${formattedMinutes}:${formattedSeconds}`;
  },

  // 获取书本信息
  getBookInco() {
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return this.setData({ isLoginMask: true });

    let bookId = this.data.postId;
    let that = this;
    wx.request({
      url: `https://api-kitap.qiyat.cn/kitapCon/${bookId}`,
      header: app.header(),
      success(res) {
        if (res.statusCode) {
          app.globalData.kitapCon = res.data;
          that.setData({ kitapCon: res.data });
        }
      },
    });
  },

  // 获取音频
  getAudio() {
    let bookId = this.data.postId;
    let pageNo = this.data.pageNo;
    let pageSize = this.data.pageSize;
    let that = this;
    wx.request({
      url: 'https://api-kitap.qiyat.cn/getAudio',
      method: 'GET',
      data: { bookId, pageNo, pageSize },
      success(res) {
        that.setData({ 
          audioList: that.data.audioList.concat(res.data.data),
          totalPage : res.data.totalPage, totalCount: res.data.totalCount
        })
      },
    });
  },

  // 播放/暂停
  play() {

    // 如果正在播放音频时停止音频
    if (audioInfo.isPlaying) {
      audioInfo.isPlaying = false;
      this.setData({ isPlaying: false });
      
      app.globalData.isLittleDrawingVisible = false;
      return audioInfo.bgAudio.pause();
    } else if (!audioInfo.isPlaying) {
      audioInfo.isPlaying = true;
      this.setData({ isPlaying: true,  });
      
      app.globalData.isLittleDrawingVisible = true;
      return audioInfo.bgAudio.play();
    }

    // 强制同步最新状态（防止意外情况）
    audioInfo.isPlaying = !audioInfo.isPlaying;
    audioInfo.playId = this.data.audioList[0].id;
    this.setData({ isPlaying: audioInfo.isPlaying });
    
    audioInfo.bgAudio.onPlay(() => {
      audioInfo.isPlaying = true;
      this.setData({ isPlaying: true });
      console.log('音频开始播放')
    })
    
    audioInfo.bgAudio.onPause(() => {
      audioInfo.isPlaying = false;
      this.setData({ isPlaying: false });
      console.log('音频暂停')
    })

  },

  // 停止 未用
  stop() {
    console.log("stop:: 按钮 ~")
    // audioInfo.isPlaying = false;
  },

  // 切换音频
  switchSong(e) {
    // 检查是否免费或者是否购买会员
    let isFree = this.data.kitapCon.is_free;
    if(isFree==1 && !app.globalData.isVIPAuthority) return this.setData({openList: false, playAllMask: true});

    const audioPost = e.currentTarget.dataset.item;
    this.setData({ openList: false });
    audioInfo.bgAudio.stop();

    // 创建后台播放
    audioInfo.bgAudio = wx.getBackgroundAudioManager()
    audioInfo.bgAudio.title = audioPost.name;
    audioInfo.bgAudio.singer = audioPost.chapter_name;
    audioInfo.bgAudio.coverImgUrl = this.data.kitapCon.cover_wx_url;
    audioInfo.bgAudio.src = audioPost.wx_url;
    audioInfo.playId = audioPost.id;
    audioInfo.isPlaying = true;
    this.setData({ isPlaying: true, playId: audioPost.id }); // 显式设置状态
    
  },

  // 打开集
  onList() {
    this.setData({ openList: true });
  },

  // 下一首
  nextOne() {
    // 检查是否免费或者是否购买会员
    let isFree = this.data.kitapCon.is_free;
    if(isFree==1 && !app.globalData.isVIPAuthority) return this.setData({playAllMask: true})

    const { audioList, currentSong } = this.data;
    if (audioList.length === 0) return; // 没有歌曲时直接返回

    // 找到当前歌曲的索引
    const currentIndex = audioList.findIndex(item => item.id === audioInfo.playId);
    
    // 计算下一首的索引（支持循环播放）
    const nextIndex = (currentIndex + 1) % audioList.length;
    const nextSong = audioList[nextIndex];
    audioInfo.bgAudio.stop();

    // 创建后台播放
    audioInfo.bgAudio = wx.getBackgroundAudioManager()
    audioInfo.bgAudio.title = nextSong.name;
    audioInfo.bgAudio.singer = nextSong.chapter_name;
    audioInfo.bgAudio.coverImgUrl = this.data.kitapCon.cover_wx_url;
    audioInfo.bgAudio.src = nextSong.wx_url;
    audioInfo.playId = nextSong.id;

    // 更新数据并播放
    this.setData({
      currentSong: nextSong,
      playId: nextSong.id,
      isPlaying: audioInfo.isPlaying
    });

    // 更新总时长
    this.checkDuration();
  },

  // 上一首
  previousOne() {
    // 检查是否免费或者是否购买会员
    let isFree = this.data.kitapCon.is_free;
    if(isFree==1 && !app.globalData.isVIPAuthority) return this.setData({playAllMask: true})

    const { audioList, currentSong } = this.data;
    if (audioList.length === 0) return;

    const currentIndex = audioList.findIndex(item => item.id === audioInfo.playId);
    
    // 计算上一首的索引（支持循环播放）
    const prevIndex = (currentIndex - 1 + audioList.length) % audioList.length;
    const prevSong = audioList[prevIndex];
    audioInfo.bgAudio.stop();

    // 创建后台播放
    audioInfo.bgAudio = wx.getBackgroundAudioManager()
    audioInfo.bgAudio.title = prevSong.name;
    audioInfo.bgAudio.singer = prevSong.chapter_name;
    audioInfo.bgAudio.coverImgUrl = this.data.kitapCon.cover_wx_url;
    audioInfo.bgAudio.src = prevSong.wx_url;
    audioInfo.playId = prevSong.id;

    this.setData({
      currentSong: prevSong,
      playId: prevSong.id,
      isPlaying: audioInfo.isPlaying
    });

    // 更新总时长
    this.checkDuration();
  },

  // 添加书架
  addToBookList() {
    let userInfo = wx.getStorageSync('userInfo')

    this.setData({ 'kitapCon.is_favorites': !this.data.kitapCon.is_favorites })
    let that = this;

    let book_id = this.data.postId;
    let user_id = userInfo.user.id;
    let type = 1;
    wx.request({
      url: `${app.globalData.API_URL}/favorites`,
      method: 'POST',
      header: app.header(),
      data: { book_id, user_id, type },
      success(res) {
        // favoritesDialogMessage: res.data
        that.setData({ notificationShow: true,  notificationMessage: res.data.message });
      }
    })
  },

  // 关闭收藏提示对话框
  onfavoritesClose() {
    this.setData({ favoritesDialog: false })
  },

  // 快进15秒
  FastForward15() {
    // 确保音频实例存在
    if (!audioInfo.bgAudio) {
      console.error('音频实例未初始化');
      return;
    }

    // 获取实时音频信息
    const currentTime = audioInfo.bgAudio.currentTime;
    const duration = audioInfo.bgAudio.duration; // 动态获取总时长

    // 边界检查
    if (isNaN(duration) || duration <= 0) {
      console.error('音频时长无效:', duration);
      return;
    }
    
    let newTime = currentTime + 15;
    if (newTime > duration) newTime = duration;

    // 使用官方API进行跳转
    audioInfo.bgAudio.seek(newTime)
  },

  // 退进15秒
  Advance15() {
    if (!audioInfo.bgAudio) {
      console.error('音频实例未初始化');
      return;
    }
  
    // 获取当前播放时间
    let currentPosition = audioInfo.bgAudio.currentTime;
    const newPosition = Math.max(0, currentPosition - 15); // 确保不小于0
  
    // 执行跳转
    audioInfo.bgAudio.seek(newPosition);
  },

  // 手动进度条
  sliderChange(e) {
    var second = e.detail.value;
    audioInfo.bgAudio.seek(second);

    let formattedTime = this.formatTime(second);
    this.setData({
      currentTime: formattedTime, // 格式化当前时间
      progress: second, // 更新进度条
    });
  },

  // 手动进度条拖动过程中
  sliderChangeing(e) {
    var second = e.detail.value;
    audioInfo.bgAudio.seek(second);

    let formattedTime = this.formatTime(second);
    this.setData({
      currentTime: formattedTime, // 格式化当前时间
      progress: second, // 更新进度条
    });
  },

  onReady() {
    // console.log("onReady")
  },

  onHide() {
    // 保存当前状态到全局
    audioInfo = {
      isPlaying: this.bgAudio.paused ? false : true,
      currentTime: this.bgAudio.currentTime,
      src: this.bgAudio.src
    };
  },
  
  onUnload() {
    // 页面销毁时释放资源
    // this.bgAudio.destroy();
  },

  // 打开定时
  onTiming() {
    this.setData({ openTiming: !this.data.openTiming, timingChecked: AppTiming.timingCheckedChange })
  },

  // 关闭定时框
  onCloseTiming() {
    if(!AppTiming.timingCheckedChange) {
      this.setData({ timingValue: 0, timingActive: 2 })
    }
    this.setData({ openTiming: false })
  },

  // 切换定时
  timingChange(e) {
    let timingActive = e.currentTarget.dataset.item;
    AppTiming.timingType = timingActive;
    this.setData({ timingValue: 0 })
    let timingText = '';
    if(timingActive == 1) {
      if(AppTiming.secondsNoFormat > 0) {
        for(let i of this.data.timingTime) {
          if(i.value == AppTiming.timingTime) {
            this.setData({ timingValue: i.id })
          }
        }
      }
      timingText = 'ۋاقىت'
    } else if( timingActive == 2 ) {
      if(AppTiming.secondsNoFormat == 0) {
        for(let i of this.data.timingJi) {
          if(i.value == AppTiming.timingJi) {
            this.setData({ timingValue: i.id })
          }
        }
      }
      timingText = 'قىسىم'
    }

    
    this.setData({ timingActive: timingActive, timingText: timingText })
  },

  // 定时按钮 时间、集
  onClickTiming(e) {
    // 时间
    if(this.data.timingActive == 1) {
      AppTiming.timingTime = e.currentTarget.dataset.item.value
      this.setData({ timingJiValue: 0 })
      let timingPost = e.currentTarget.dataset.item.value * 60;
      AppTiming.secondsNoFormat = timingPost;
      this.countdown(timingPost)
    }
    
    // 集
    if(this.data.timingActive == 2) {
      let playId = audioInfo.playId;
      let audioList = this.data.audioList;
      audioInfo.playCurrentIndex = audioList.findIndex(item => item.id === playId); // 当前播放音频 ID
      audioInfo.totalIndex = audioList.length;

      let timingJiValue = e.currentTarget.dataset.item.value;
      
      AppTiming.timingJi = timingJiValue;
      this.setData({ timingJiValue: timingJiValue });

      AppTiming.timingTime = '';
    }
    
    let timingValue = e.currentTarget.dataset.item.id;
    AppTiming.timingCheckedChange  = true;
    this.setData({ timingValue: timingValue, timingChecked: true });
  },

  // 定时开关
  timingCheckedChange() {
    // 时间设置 0  // 管理时间
    if(AppTiming.secondsNoFormat > 0) {
      clearInterval(this.timer);
      this.setData({ timingTimeValue: '' })
      AppTiming.secondsNoFormat = 0;
      AppTiming.timingCheckedChange = !AppTiming.timingCheckedChange;
    }

    // 集管理
    if(AppTiming.timingJi > 0 && AppTiming.timingCheckedChange) {
      this.setData({ timingValue: 0, timingJiValue: 0 })
      AppTiming.timingJi = -1;
      AppTiming.timingCheckedChange = !AppTiming.timingCheckedChange;
    };
  },

  // 倒计时
  timer : null,
  countdown(seconds, callback) {
    // 先清理之前的倒计时
    if (this.timer) {
      clearInterval(this.timer);
    }

    // let remaining = seconds;
    
    if(AppTiming.secondsNoFormat == 0) AppTiming.secondsNoFormat = seconds;
    let remaining = AppTiming.secondsNoFormat;
    
    this.timer = setInterval(() => {
      this.timingTimeFormatTime(remaining)
      remaining--;
      
      if (remaining < 0) {
        clearInterval(this.timer);
        callback && callback();

        audioInfo.isPlaying = false;
        this.setData({ isPlaying: false });
        return audioInfo.bgAudio.pause();
      }
    }, 1000);
  },

  // 倒计时间格式
  timingTimeFormatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    
    // 补零显示，如 8:05 而不是 8:5
    const formattedSeconds = remainingSeconds < 10 
      ? `0${remainingSeconds}` 
      : remainingSeconds;
    
    // AppTiming.timingTime = `${minutes}:${formattedSeconds}`;
    if (seconds > 0) AppTiming.secondsNoFormat = seconds
    return this.setData({ timingTimeValue: `${minutes}:${formattedSeconds}` })
  },

  // 倍速点击
  onSpeed() {
    const speedOptions = [
      { label: '0.5x', value: 0.5 },
      { label: '1x', value: 1 },
      { label: '1.5x', value: 1.5 },
      { label: '2x', value: 2 },
    ];

    let that = this;
    wx.showActionSheet({
      itemList: speedOptions.map(item => item.label),
      success(res) {
        const selectedSpeed = speedOptions[res.tapIndex].value;
        that.setPlaybackSpeed(selectedSpeed);
      },
      fail(err) {
        console.error('倍速选择失败:', err);
      }
    });
  },

  // 设置播放速度
  setPlaybackSpeed(speed) {
    audioInfo.speed = speed;
    this.setData({ speed: speed });
    if (!audioInfo.bgAudio) return;

    if (audioInfo.bgAudio) {
      audioInfo.bgAudio.playbackRate = speed;
    }
  },

  // 本页分享
  onShare() {
    // 自定义分享内容
    wx.showShareMenu({
      withShareTicket: true, // 开启带shareTicket的分享
      menus: ['shareAppMessage', 'shareTimeline'] // 仅显示转发给好友菜单
    });
  },

  // 检查用户登录
  isLogin() {
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      this.setData({ isLoginMask: true })
    }
  },

  // 隐藏登录提示组件
  changeLoginMask(e) {
    this.getBookInco();
    this.addpreview();
    this.setData({ isLoginMask: e.detail.isLoginMask, notificationShow: true })
  },

  // 加入预览
  addpreview() {
    let userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) return this.setData({ isLoginMask: true });

    let user_id = userInfo.user.id;
    let data = { book_id: parseInt(this.data.postId, 10), user_id: user_id }
    wx.request({
      url: `${API_URL}/previewStore`,
      method: 'POST',
      header: app.header(),
      data: data,
      success: res => {
        if(res.statusCode == 200) {
          console.log("已加入预览表 ~")
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: `${this.data.kitapCon.name}`,
      path: '/pages/audioPlay/audioPlay',
      imageUrl: `${this.data.kitapCon.cover_wx_url}`
    };
  }

});